<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 */

namespace app\model\member;

use app\model\system\Cron;
use think\facade\Cache;
use app\model\BaseModel;

/**
 * 会员等级
 */
class MemberLevel extends BaseModel
{

    public $level_change_type = [
        'upgrade' => '自动升级',
        'buy' => '付费购卡',
        'adjust' => '商家调整',
        'expire' => '到期降级'
    ];

    public $level_time = [
        'week' => '一周',
        'month' => '一月',
        'quarter' => '一季',
        'year' => '一年',
    ];

    /**
     * 添加会员等级
     *
     * @param array $data
     */
    public function addMemberLevel($data)
    {
        $is_default = $data[ 'is_default' ] ?? 0;

        //判断是否重复
        $count = model('member_level')->getCount([ [ 'growth', '=', $data[ 'growth' ] ] ]);
        //if ($count > 0) return $this->error('', '等级成长值重复');
        $count = model('member_level')->getCount([ [ 'level_name', '=', $data[ 'level_name' ] ] ]);
        if ($count > 0) return $this->error('', '等级名称已存在');

        if ($is_default == 1) {
            $this->refreshLevel();
        }
        $res = model('member_level')->add($data);
        $this->refreshSort();
        Cache::tag("member_level")->clear();
        return $this->success($res);
    }

    /**
     * 修改会员等级(不允许批量处理)
     *
     * @param array $data
     * @param array $condition
     */
    public function editMemberLevel($data, $condition)
    {
        $is_default = $data[ 'is_default' ] ?? 0;

        //判断是否重复
//        $count = model('member_level')->getCount([['growth', '=', input('growth', 0)]]);
//        if($count > 0) return $this->error('', '等级成长值重复');
//        $count = model('member_level')->getCount([['level_name', '=', $data['level_name']]]);
//        if($count > 0) return $this->error('', '等级名称重复');

        if ($is_default == 1) {
            $this->refreshLevel();
        }
        $res = model('member_level')->update($data, $condition);

        //$check_condition = array_column($condition, 2, 0);
        //model('member')->update([ "member_level_name" => $data[ "level_name" ] ], [ [ "member_level", "=", $check_condition[ "level_id" ] ] ]);
        $this->refreshSort();
        Cache::tag('member_level')->clear();
        return $this->success($res);
    }

    /**
     * 刷新会员等级排序
     */
    private function refreshSort()
    {
        $list = model('member_level')->getList([], 'level_id, growth', 'growth asc');
        foreach ($list as $k => $v) {
            model('member_level')->update([ 'sort' => $k ], [ [ 'level_id', '=', $v[ 'level_id' ] ] ]);
        }
    }

    /**
     * 刷新会员等级
     */
    private function refreshLevel()
    {
        model('member_level')->update([ 'is_default' => 0 ], [ [ 'is_default', '=', 1 ] ]);
    }

    /**
     * 删除会员等级
     * @param array $condition
     */
    public function deleteMemberLevel($condition)
    {
        $res = model('member_level')->delete($condition);
        $this->refreshSort();
        Cache::tag("member_level")->clear();
        return $this->success($res);
    }

    /**
     * 获取会员等级信息
     *
     * @param array $condition
     * @param string $field
     */
    public function getMemberLevelInfo($condition = [], $field = '*')
    {

        $data = json_encode([ $condition, $field ]);
        $cache = Cache::get("member_level_getMemberLevelInfo_" . $data);
        if (!empty($cache)) {
            return $this->success($cache);
        }
        $info = model('member_level')->getInfo($condition, $field);
        Cache::tag("member_level")->set("member_level_getMemberLevelInfo_" . $data, $info);
        return $this->success($info);
    }

    /**
     * 获取会员等级列表
     *
     * @param array $condition
     * @param string $field
     * @param string $order
     * @param string $limit
     */
    public function getMemberLevelList($condition = [], $field = '*', $order = 'sort asc, level_id asc', $limit = null)
    {

        $data = json_encode([ $condition, $field, $order, $limit ]);
        $cache = Cache::get("member_level_getMemberLevelList_" . $data);

        if (!empty($cache)) {
            return $this->success($cache);
        }

        $list = model('member_level')->getList($condition, $field, $order, '', '', '', $limit);
        Cache::tag("member_level")->set("member_level_getMemberLevelList_" . $data, $list);

        return $this->success($list);
    }

    /**
     * 获取会员等级分页列表
     *
     * @param array $condition
     * @param number $page
     * @param string $page_size
     * @param string $order
     * @param string $field
     */
    public function getMemberLevelPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = 'sort asc, level_id asc', $field = '*')
    {

        $data = json_encode([ $condition, $field, $order, $page, $page_size ]);
        $cache = Cache::get("member_level_getMemberLevelPageList_" . $data);
        if (!empty($cache)) {
            return $this->success($cache);
        }
        $list = model('member_level')->pageList($condition, $field, $order, $page, $page_size);
        Cache::tag("member_level")->set("member_level_getMemberLevelPageList_" . $data, $list);
        return $this->success($list);
    }

    /**
     * 设置默认等级
     * @param unknown $level_id
     */
    public function setDefaultLevel($level_id)
    {
        model('member_level')->update([ 'is_default' => 1 ], [ [ 'level_id', '=', $level_id ] ]);
        model('member_level')->update([ 'is_default' => 0 ], [ [ 'level_id', '<>', $level_id ] ]);
        Cache::tag("member_level")->clear();
        return $this->success();
    }


    /**
     * 添加会员卡变更记录
     * @param $member_id 变更会员
     * @param $site_id 站点id
     * @param $after_level 变更之后的会员卡
     * @param $action_uid 操作人
     * @param $action_type 操作人类型
     * @param $action_name 操作人昵称
     * @param string $action_desc 描述
     */
    public function addMemberLevelChangeRecord($member_id, $site_id, $after_level, $expire_time, $change_type, $action_uid, $action_type, $action_name, $action_desc = '',$member_card_type=1){
        model('member_level_records')->startTrans();

        try {
            $member_info = model('member')->getInfo([ ['member_id', '=', $member_id] ], 'member_level,member_level_name,member_level_type,level_expire_time');

            $level_info = model('member_level')->getInfo([ ['level_id', '=', $after_level] ], 'level_id,level_name,level_type');

            if ($member_info['member_level'] == $level_info['level_id']) {
                model('member_level_records')->rollback();
                return $this->success('', '会员卡未发生变更');
            }

            $prev_record = model('member_level_records')->getFirstData([ ['member_id', '=', $member_id] ], 'id', 'change_time desc');
            // 添加变更记录
            $data = [
                'member_id' => $member_id,
                'site_id' => $site_id,
                'before_level_id' => $member_info['member_level'],
                'before_level_name' => $member_info['member_level_name'],
                'before_level_type' => $member_info['member_level_type'],
                'before_expire_time' => $member_info['level_expire_time'],
                'after_level_id' => $level_info['level_id'],
                'after_level_name' => $level_info['level_name'],
                'after_level_type' => $level_info['level_type'],
                'prev_id' => $prev_record['id'] ?? 0,
                'change_time' => time(),
                'action_uid' => $action_uid,
                'action_type' => $action_type,
                'action_name' => $action_name,
                'action_desc' => $action_desc,
                'change_type' => $change_type,
                'change_type_name' => $this->level_change_type[$change_type]
            ];

            model('member_level_records')->add($data);

            if ($member_card_type==1){
                $level_name = '个人会员';
            } else {
                $level_name = '门店会员';
            }
            // 变更会员等级
            model('member')->update([
                'member_level' => $level_info['level_id'],
                'member_level_name' => $level_name,
                'member_level_type' => $level_info['level_type'],
                'member_card_type'  => $member_card_type,
                'level_expire_time' => $expire_time,
                'open_level_time'   => time()
            ], [ ['member_id','=',$member_id] ]);

            /*$cron = new Cron();
            $cron->deleteCron([ ['event', '=', 'MemberLevelAutoExpire'], ['relate_id', '=', $member_id ] ]);
            if ($level_info['level_type']) {
                $cron->addCron(1, 0, "会员卡自动过期", "MemberLevelAutoExpire", $expire_time, $member_id);
            }*/
            Cache::tag("member_level_records")->clear();
            model('member_level_records')->commit();
            return $this->success();
        } catch (\Exception $e) {
            model('member_level_records')->rollback();
            return $this->error('', $e->getMessage());
        }
    }

    /**
     * 获取会员会员卡变更记录
     * @param array $condition
     * @param int $page
     * @param int $list_rows
     * @param string $field
     * @param string $order
     * @param string $alias
     * @param array $join
     * @param null $group
     * @return array
     */
    public function getMemberLevelRecordPageList($condition = [], $page = 1, $list_rows = PAGE_LIST_ROWS, $field = '*', $order = 'change_time desc',  $alias = 'a', $join = [], $group = null){
        $data  = json_encode([$condition, $field, $order, $page, $list_rows, $alias, $join, $group]);
        $cache = Cache::get("getMemberLevelRecordPageList" . $data);
        if (!empty($cache)) {
            return $this->success($cache);
        }
        $list = model('member_level_records')->pageList($condition, $field, $order, $page, $list_rows, $alias, $join, $group);
        Cache::tag("member_level_records")->set("getMemberLevelRecordPageList" . $data, $list);
        return $this->success($list);
    }

    /**
     * 会员卡过期
     * @param $member_id
     */
    public function memberLevelExpire($id){
        $member_info = model('member_level_records')->getInfo([ ['id', '=', $id] ], '*');
        $member_id = $member_info['member_id'];
        $member = model('member')->getInfo([ ['member_id', '=', $member_id] ], 'member_id,nickname');
        if (!empty($member_info) && !empty($member_info['level_expire_time']) && $member_info['level_expire_time'] < time()) {

            // 如果之前的免费卡不存在
            $level_info = model('member_level')->getFirstData([ ['level_id', '=', $member_info['after_level_id']]], '*', 'growth desc');

            if (!empty($level_info)) {
                $this->addMemberLevelChangeRecord($member_id, $member_info['site_id'], $level_info['level_id'], 0, 'expire', $member_id, 'member', $member['nickname']);
                $member_account = new MemberAccount();
                //赠送红包
                if ($level_info['send_balance'] > 0) {
                    $member_account->addMemberAccount($member_info['site_id'], $member_info['member_id'], 'balance', $level_info['send_balance'], 'upgrade', '会员升级得红包' . $level_info['send_balance'], '会员升级得红包' . $level_info['send_balance']);
                }
                //赠送积分
                if ($level_info['send_point'] > 0) {
                    $member_account->addMemberAccount($member_info['site_id'], $member_info['member_id'], 'point', $level_info['send_point'], 'upgrade', '会员升级得积分' . $level_info['send_point'], '会员升级得积分' . $level_info['send_point']);
                }
            }
        }
    }
}